import java.util.PriorityQueue;

//定时任务类--保存任务（绝对时间+内容）
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;

    public MyTimerTask(Runnable runnable, long delaytime) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delaytime;//传入延迟时间（相对时间），保存要执行时的绝对时间
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);//小根堆。队首元素是最近的时间
    }
}

//定时器类-->保存任务+扫描时间
class MyTimer{
    //1、优先级队列保存任务
    private PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
    Object locker=new Object();

    //2、schedule传参
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            queue.offer(new MyTimerTask(runnable,delay));
            locker.notify();
        }
    }

    //3、构造方法里扫描线程
    public MyTimer(){
        Thread t=new Thread(()->{
            //需要不停的扫描查看是否到达时间
            while (true){
                synchronized (locker){
                    //1、拿到队首任务
                    if(queue.isEmpty()){
                        //阻塞等待--wait<--synchronized监视器锁-->schedule()一个线程给队列添加元素，扫描线程又操作队列-->不安全刚好要加锁
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    MyTimerTask task=queue.peek();
                }
                }


        });

        t.start();
    }
}


public class demo6 {
    public static void main(String[] args) {

    }
}
